import glob
import json
import time

import cv2
import numpy as np
import requests
import base64

def call_flask_detect(image_path):
    # 1 构造请求数据
    # # 读取图片并进行 base64 编码
    # with open(image_path, "rb") as image_file:
    #     base64_str = base64.b64encode(image_file.read()).decode()

    img_np = cv2.imread(image_path)
    # img_np = cv2.resize(img_np, None, fx=0.1,fy=0.1)
    # _, buffer = cv2.imencode('.jpg', img_np)
    base64_str = base64.b64encode(cv2.imencode('.jpg', img_np)[1].tobytes()).decode() # numpy to base64_str

    print(len(base64_str))
    url_str = 'http://127.0.0.1:5000/detect'
    payload = {
        'image_base64': base64_str,
        'function': 'hanhou', #  焊前线束：hanqianxianshu  焊后：hanhou
        # 'product': '519' # 产品型号 517 518 519 520
        'product': '618'  # 产品型号
    }
    # payload = {}
    # 2 发送 POST 请求
    t1 = time.time()
    # response = requests.post('http://localhost:5000/detect', json=payload,timeout=5,verify=False)
    response = requests.post(url_str, json=payload, timeout=50, verify=False)
    # response = requests.post('http://127.0.0.1:5000/detect', data=json.dumps({'res':0}), verify=False)
    # response = requests.get('http://localhost:5000/',  verify=False)
    print(f'time {time.time()-t1}')
    # 3 处理响应
    if response.status_code == 200:
        res_dict = response.json()
        funct, prod, show_img_base64, result = res_dict['function'], res_dict['product'], res_dict['show_img_base64'], res_dict['result']
        if funct == 'hanqianxianshu':
            template_names = res_dict['other']['template_names']
            predict_names = res_dict['other']['predict_names']
        res_dict['show_img_base64'] = len(res_dict['show_img_base64'])
        print(json.dumps(res_dict, indent=4, sort_keys=True, ensure_ascii=False))
        show_img_array = np.frombuffer(base64.b64decode(show_img_base64), dtype=np.uint8) #
        show_img = cv2.imdecode(show_img_array, cv2.IMREAD_COLOR)
        cv2.imwrite(f'Pictures\client\{funct}_{prod}_{time.time()}.jpg', show_img)
        # return response.json()
    else:
        print(f"Error: {response.status_code}")
        print(f"Error: {response.json()['error']}")
        return None

# 测试客户端
if __name__ == '__main__':
    # image_path = r"D:\code\git\zxc\project_fubahanxi\Pictures\2.jpg"
    # glob_str = r"D:\data\240815fubahanxi\caitu\20241023houng\NG\*.jpg" # 1008-093003
    glob_str = r"D:\data\240815fubahanxi\caitu\20241021qianNG\*.jpg"
    # glob_str = r'C:\Users\admin\MVS\Data\xx_d3_guang_Image_20241031144246139.jpg'
    imgs_paths = glob.glob(glob_str)
    for image_path in imgs_paths:
        t1 = time.time()
        result = call_flask_detect(image_path)
        print(time.time()-t1)
        # print(result)
